package com.zhengshang.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhengshang.api.domain.AppGasStation;
import com.zhengshang.api.service.IAppGasStationService;
import com.zhengshang.common.annotation.RepeatSubmit;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.model.LoginAppUser;
import com.zhengshang.common.enums.UserStatus;
import com.zhengshang.common.utils.DateUtils;
import com.zhengshang.common.utils.http.HttpUtils;
import com.zhengshang.common.utils.sign.SignMD5Util;
import com.zhengshang.security.service.TokenService;
import com.zhengshang.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.TreeMap;

/**
 * @author HY
 * @version 1.0.0
 * @ClassName ViolationController.java
 * @Description TODO
 * @createTime 2021年04月08日 09:07
 */
@Api(tags = "加油接口")
@RestController
@RequestMapping("/gas")
public class GasController extends BaseController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IAppGasStationService appGasStationService;

    @ApiOperation(value = "查询油站状态油价接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lon", value = "经度", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "lat", value = "纬度", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页码（从1开始）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（最小为1，最大为100）", required = false, dataType = "int", paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('app:gas:all')")
    @PostMapping("/queryPriceByPhone")
    public AjaxResult queryPriceByPhone(
            @RequestParam Double lon,
            @RequestParam Double lat,
            @RequestParam Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request, HttpServletResponse response){

        if (lon == null || lat == null || pageNum == null || pageNum.intValue() <= 0 || (pageSize != null && pageSize.intValue() < 1)) {
            return AjaxResult.error("参数错误");
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageSize.intValue() > 100) {
            pageSize = 100;
        }
        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            AppGasStation appGasStation = new AppGasStation();
            appGasStation.setGasAddressLongitude(lon);
            appGasStation.setGasAddressLatitude(lat);
            appGasStation.getParams().put("pageNum", pageNum);
            appGasStation.getParams().put("pageSize", pageSize);
            List<AppGasStation> appGasStationList = appGasStationService.selectAppGasStationByLonLat(appGasStation);
            String gasIds = "";
            for (AppGasStation gasStation : appGasStationList) {
                gasIds += gasStation.getGasId() + ",";
            }

            TreeMap<String, String> param = new TreeMap<>();
            param.put("app_key", AppConstant.GAS_APP_KEY);
            param.put("timestamp", DateUtils.getNowDate().getTime() + "");
            param.put("platformType", AppConstant.GAS_CHANNEL_ID);
            param.put("gasIds", gasIds);
            param.put("phone", loginAppUser.getAppUser().getPhonenumber());
            param.put("sign", SignMD5Util.getSignNL(param, AppConstant.GAS_APP_SECRET));
            String result = HttpUtils.sendPost(AppConstant.GAS_QUERY_PRICE_BY_PHONE_URL, HttpUtils.getParam(param));
            JSONObject resultObj = JSONObject.parseObject(result);
            if (resultObj.getIntValue("code") == 100) {
                //授权登录
                platformLoginSimpleAppV4(loginAppUser.getAppUser().getPhonenumber());
                //授权登录后再次请求接口
                result = HttpUtils.sendPost(AppConstant.GAS_QUERY_PRICE_BY_PHONE_URL, HttpUtils.getParam(param));
                resultObj = JSONObject.parseObject(result);
            }
            if (resultObj.getIntValue("code") == 200) {
                JSONArray gasList = resultObj.getJSONArray("result");

//                //TODO 测试站点下线，后续删除
//                gasList.remove(2);

                gasFor: for (AppGasStation gasStation : appGasStationList) {
                    for (int i = 0; i < gasList.size(); i++) {
                        if (gasStation.getGasId().equals(gasList.getJSONObject(i).getString("gasId"))) {
                            gasStation.setGasName(gasList.getJSONObject(i).getString("gasName"));
                            gasStation.setBusinessHours(gasList.getJSONObject(i).getString("businessHours"));
                            gasStation.setOilPriceList(gasList.getJSONObject(i).getJSONArray("oilPriceList"));
                            //如果找到数据，直接进入外层循环的下次循环
                            continue gasFor;
                        }
                    }
                    //如果找不到数据，即为下架，并标记为删除数据
                    gasStation.setDelFlag(UserStatus.DELETED.getCode());
                    appGasStationService.updateAppGasStation(gasStation);
                }
                logger.info("<gas.queryPriceByPhone>", resultObj);
                return AjaxResult.success("获取成功", appGasStationList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("获取失败");
    }

    @ApiOperation(value = "平台授权登录")
    @PreAuthorize("@ss.hasPermi('app:gas:all')")
    @RepeatSubmit
    @PostMapping("/platformLoginSimpleAppV4")
    public AjaxResult platformLoginSimpleAppV4(
            HttpServletRequest request, HttpServletResponse response){
        try {

            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            JSONObject result = platformLoginSimpleAppV4(loginAppUser.getAppUser().getPhonenumber());
            if (result.getIntValue("code") == 10041) {
                logger.error("IP已变更，请将新IP加入白名单后再试！");
                return AjaxResult.error("IP有变化，请联系管理员");
            } else if (result.getIntValue("code") == 200) {
                return AjaxResult.success("授权成功", result.getJSONObject("result").getString("token"));
            }
            logger.error("<gas.platformLoginSimpleAppV4>授权失败：{}", result.getString("message"));
            return AjaxResult.error("授权失败：" + result.getString("message"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<gas.platformLoginSimpleAppV4>授权异常：{}", e.getMessage());
            return AjaxResult.error("授权异常，请联系管理员");
        }
    }

    @ApiOperation(value = "查询用户的优惠券接口")
    @PreAuthorize("@ss.hasPermi('app:gas:all')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码（从1开始）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（最小为1，最大为100）", required = false, dataType = "int", paramType = "query")
    })
    @RepeatSubmit
    @PostMapping("/couponsWithPage")
    public AjaxResult couponsWithPage(
            @RequestParam Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request, HttpServletResponse response){

        if (pageNum == null || pageNum.intValue() <= 0 || (pageSize != null && pageSize.intValue() < 1)) {
            return AjaxResult.error("参数错误");
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageSize.intValue() > 100) {
            pageSize = 100;
        }
        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            TreeMap<String, String> param = new TreeMap<>();
            param.put("app_key", AppConstant.GAS_APP_KEY);
            param.put("platform", AppConstant.GAS_CHANNEL_ID);
            param.put("timestamp", DateUtils.getNowDate().getTime() + "");
            param.put("mobilePhone", loginAppUser.getAppUser().getPhonenumber());
            param.put("pageIndex", pageNum + "");
            param.put("pageSize", pageSize + "");
            param.put("sign", SignMD5Util.getSignNL(param, AppConstant.GAS_APP_SECRET));
            String result = HttpUtils.sendPost(AppConstant.GAS_COUPONS_WITHPAGE_URL, HttpUtils.getParam(param));
            JSONObject resultObj = JSONObject.parseObject(result);
            return AjaxResult.success(resultObj);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<gas.couponsWithPage>查询优惠券异常：{}", e.getMessage());
            return AjaxResult.error("查询优惠券异常，请联系管理员");
        }
    }

    @ApiOperation(value = "优惠券兑换接口")
    @PreAuthorize("@ss.hasPermi('app:gas:all')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "优惠券兑换码", required = true, dataType = "String", paramType = "query"),
    })
    @RepeatSubmit
    @PostMapping("/useCodeByMobilePhone")
    public AjaxResult useCodeByMobilePhone(
            @RequestParam String code,
            HttpServletRequest request, HttpServletResponse response){

        if (StringUtils.isBlank(code)) {
            return AjaxResult.error("参数错误");
        }

        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            TreeMap<String, String> param = new TreeMap<>();
            param.put("app_key", AppConstant.GAS_APP_KEY);
            param.put("platform", AppConstant.GAS_CHANNEL_ID);
            param.put("timestamp", DateUtils.getNowDate().getTime() + "");
            param.put("mobilePhone", loginAppUser.getAppUser().getPhonenumber());
            param.put("code", code);
            param.put("sign", SignMD5Util.getSignNL(param, AppConstant.GAS_APP_SECRET));
            String result = HttpUtils.sendPost(AppConstant.GAS_USECODE_BY_MOBILEPHONE_URL, HttpUtils.getParam(param));
            JSONObject resultObj = JSONObject.parseObject(result);
            if (resultObj.getIntValue("code") == 200) {
                return AjaxResult.success("优惠券兑换成功");
            }
            return AjaxResult.error("优惠券兑换失败");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<gas.useCodeByMobilePhone>优惠券兑换失败：{}", e.getMessage());
            return AjaxResult.error("优惠券兑换失败，请联系管理员");
        }
    }

    @ApiOperation(value = "订单接口")
    @PreAuthorize("@ss.hasPermi('app:gas:all')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "支付开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "支付结束时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "订单状态", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderId", value = "订单号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页码（从1开始）", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（最小为1，最大为100）", required = false, dataType = "int", paramType = "query")
    })
    @RepeatSubmit
    @PostMapping("/platformOrderInfoV2")
    public AjaxResult platformOrderInfoV2(
            @RequestParam(required = false) String beginTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String orderStatus,
            @RequestParam(required = false) String orderId,
            @RequestParam Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request, HttpServletResponse response
    ){

        if (pageNum == null || pageNum.intValue() <= 0 || (pageSize != null && pageSize.intValue() < 1)) {
            return AjaxResult.error("参数错误");
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageSize.intValue() > 100) {
            pageSize = 100;
        }

        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            TreeMap<String, String> param = new TreeMap<>();
            param.put("app_key", AppConstant.GAS_APP_KEY);
            param.put("orderSource", AppConstant.GAS_CHANNEL_ID);
            param.put("timestamp", DateUtils.getNowDate().getTime() + "");
            param.put("phone", loginAppUser.getAppUser().getPhonenumber());
            if (StringUtils.isNotBlank(beginTime)) param.put("beginTime", beginTime);
            if (StringUtils.isNotBlank(endTime)) param.put("endTime", endTime);
            if (StringUtils.isNotBlank(orderStatus)) param.put("orderStatus", orderStatus);
            if (StringUtils.isNotBlank(orderId)) param.put("orderId", orderId);
            param.put("pageIndex", pageNum + "");
            param.put("pageSize", pageSize + "");
            param.put("sign", SignMD5Util.getSignNL(param, AppConstant.GAS_APP_SECRET));
            String result = HttpUtils.sendPost(AppConstant.GAS_PLATFORM_ORDERINFO_V2_URL, HttpUtils.getParam(param));
            JSONObject resultObj = JSONObject.parseObject(result);
            if (resultObj.getIntValue("code") == 200) {
                resultObj.remove("code");
                resultObj.remove("message");
                return AjaxResult.success(resultObj);
            }
            return AjaxResult.error("订单查询失败");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<gas.platformOrderInfoV2>优惠券兑换失败：{}", e.getMessage());
            return AjaxResult.error("订单查询失败，请联系管理员");
        }
    }

    @ApiOperation(value = "获取H5支付页面链接")
    @PreAuthorize("@ss.hasPermi('app:gas:all')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gasId", value = "加油站ID", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gunNo", value = "油枪号", required = true, dataType = "String", paramType = "query"),
    })
    @RepeatSubmit
    @PostMapping("/getH5PayUrl")
    public AjaxResult getH5PayUrl(
            @RequestParam String gasId,
            @RequestParam String gunNo,
            HttpServletRequest request, HttpServletResponse response){

        if (StringUtils.isBlank(gasId) || StringUtils.isBlank(gunNo)) {
            return AjaxResult.error("参数错误");
        }

        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);

            //获取授权码
            TreeMap<String, String> param = new TreeMap<>();
            param.put("app_key", AppConstant.GAS_APP_KEY);
            param.put("platformId", AppConstant.GAS_CHANNEL_ID);
            param.put("timestamp", DateUtils.getNowDate().getTime() + "");
            param.put("phone", loginAppUser.getAppUser().getPhonenumber());
            param.put("sign", SignMD5Util.getSignNL(param, AppConstant.GAS_APP_SECRET));
            String result = HttpUtils.sendPost(AppConstant.GAS_GET_SECRET_CODE_URL, HttpUtils.getParam(param));
            JSONObject resultObj = JSONObject.parseObject(result);
            if (resultObj.getIntValue("code") == 200) {

                resultObj.remove("code");
                resultObj.remove("message");
                resultObj.put("platformType", AppConstant.GAS_CHANNEL_ID);
                return AjaxResult.success("获取H5支付页面链接成功", AppConstant.GAS_H5_PAY_URL.replace("PLATFORM_TYPE", AppConstant.GAS_CHANNEL_ID).replace("AUTH_CODE", resultObj.getString("result")).replace("GAS_ID", gasId).replace("GUN_NO", gunNo));
            }
            return AjaxResult.error("获取H5支付页面链接失败");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<gas.getSecretCode>获取H5支付页面链接失败：{}", e.getMessage());
            return AjaxResult.error("获取H5支付页面链接失败，请联系管理员");
        }
    }

    private JSONObject platformLoginSimpleAppV4(String phone) throws Exception {
        TreeMap<String, String> param = new TreeMap<>();
        param.put("app_key", AppConstant.GAS_APP_KEY);
        param.put("platformType", AppConstant.GAS_CHANNEL_ID);
        param.put("platformCode", phone);
        param.put("sign", SignMD5Util.getSignNL(param, AppConstant.GAS_APP_SECRET));
        String result = HttpUtils.sendPost(AppConstant.GAS_PLATFORM_LOGIN_SIMPLEAPP_V4_URL, HttpUtils.getParam(param));
//        JSONObject resultObj = JSONObject.parseObject(result);
        //token暂时没有使用的地方，暂不存储数据库
        return JSONObject.parseObject(result);
    }

}
